package com.mmlc.utils;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.responsejavabean.RequestError;
import com.androidnetframe.utils.*;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.mmlc.meimei.lichengkongjian.App;
import com.mmlc.meimei.lichengkongjian.MainActivity;
import com.mmlc.meimei.lichengkongjian.brand.BrandInfoActivity;
import com.mmlc.meimei.lichengkongjian.classify.ActivityPhotoView;
import com.mmlc.meimei.lichengkongjian.classify.FastGoodsDetailActivity;
import com.mmlc.meimei.lichengkongjian.classify.MeiQiFastBuyActivity;
import com.mmlc.meimei.lichengkongjian.classify.PhysicalStoreActivity;
import com.mmlc.meimei.lichengkongjian.classify.ProductInfoActivity;
import com.mmlc.meimei.lichengkongjian.home.WebViewActivity;
import com.mmlc.meimei.lichengkongjian.mine.LoginActivity;
import com.mmlc.meimei.lichengkongjian.mine.RegisterAccount;
import com.mmlc.network.filter.LoginOutRequestFilter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;

/**
 * Created by admin on 2018/2/4.
 */

public class WebUtils {

    public static void setWebJS(BridgeWebView webView, final Activity context, final TextView tv_title) {
        //跳转到商品详情
        webView.registerHandler("brand_store_list", new BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        try {
                            if (s == null) {
                                LogUtils.e("brand_store_list", "空");
                            } else {
                                LogUtils.e("brand_store_list", s);
                            }
                            LogUtils.e("brand_store_list", URLDecoder.decode(s.toString(), "utf-8"));
                            JSONObject json = new JSONObject(URLDecoder.decode(s.toString(), "utf-8"));
                            String goods_id = json.optString("brand_id");//商品编号ID
                            String type = json.optString("title");//标题名称
                            if (!ViewUtils.isEmpty(goods_id)) {
                                Intent intent = new Intent(context, PhysicalStoreActivity.class);
                                intent.putExtra("id", goods_id);
                                context.startActivity(intent);
                            } else
                                ToastUtils.showToast("商品不存在");
                        } catch (
                                JSONException e
                                )

                        {
                            e.printStackTrace();
                        } catch (
                                UnsupportedEncodingException e
                                )

                        {
                            e.printStackTrace();
                        }
                    }
                }

        );

        //跳转到商品详情
        webView.registerHandler("close_form", new BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        context.finish();
                    }
                }

        );
        //跳转到商品详情
        webView.registerHandler("set_page_title", new BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        try {
                            if (s == null) {
                                LogUtils.e("set_page_title", "空");
                            } else {
                                LogUtils.e("set_page_title", s);
                            }
                            LogUtils.e("set_page_title", URLDecoder.decode(s.toString(), "utf-8"));
                            JSONObject json = new JSONObject(URLDecoder.decode(s.toString(), "utf-8"));
                            String titles = json.optString("title");//标题名称
                            if (!ViewUtils.isEmpty(titles)) {
                                if (tv_title != null)
                                    tv_title.setText(titles);
                            } else
                                ToastUtils.showToast("未获取到标题");
                        } catch (
                                JSONException e
                                )

                        {
                            e.printStackTrace();
                        } catch (
                                UnsupportedEncodingException e
                                )

                        {
                            e.printStackTrace();
                        }
                    }
                }

        );
        //跳转到商品详情
        webView.registerHandler("open_new_form", new BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        try {
                            if (s == null) {
                                LogUtils.e("open_new_form", "空");
                            } else {
                                LogUtils.e("open_new_form", s);
                            }
                            LogUtils.e("open_new_form", URLDecoder.decode(s.toString(), "utf-8"));
                            JSONObject json = new JSONObject(URLDecoder.decode(s.toString(), "utf-8"));
                            String titles = json.optString("title");//标题名称
                            String url = json.optString("url");//标题名称
                            if (!ViewUtils.isEmpty(url)) {
                                Intent i = new Intent(context, WebViewActivity.class);
                                i.putExtra("title", titles).putExtra("url", url);
                                context.startActivity(i);
                            } else
                                ToastUtils.showToast("未获取到地址");
                        } catch (
                                JSONException e
                                )

                        {
                            e.printStackTrace();
                        } catch (
                                UnsupportedEncodingException e
                                )

                        {
                            e.printStackTrace();
                        }
                    }
                }

        );
        webView.registerHandler("preview_goods_img", new BridgeHandler() {
            @Override
            public void handler(String s, CallBackFunction function) {
                try {
                    JSONObject json = new JSONObject(URLDecoder.decode(s.toString(), "utf-8"));
                    int show_index = json.optInt("show_index");
                    JSONArray img_list = json.optJSONArray("img_list");
                    ArrayList<String> imgs = new ArrayList
                            <String>();
                    for (int i = 0; i < img_list.length(); i++) {
                        JSONObject jsonObject = img_list.optJSONObject(i);
                        String url = jsonObject.optString("url");
                        imgs.add(url);
                    }
                    Intent intent = new Intent(context,ActivityPhotoView.class);
                    Bundle bundle1 = new Bundle();
                    bundle1.putString("index",show_index+"");
                    bundle1.putStringArrayList("imgs",imgs);
                    intent.putExtra("bundle",bundle1);
                    context.startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        //跳转到商品详情页
        webView.registerHandler("goods_detail", new BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        try {
                            LogUtils.e("goods_detail", URLDecoder.decode(s.toString(), "utf-8"));
                            JSONObject json = new JSONObject(URLDecoder.decode(s.toString(), "utf-8"));

                            String goods_id = json.optString("goods_id");
                            int type = json.optInt("type");
                            if (!ViewUtils.isEmpty(goods_id)) {
                                if (TextUtils.equals("register", goods_id)) {
                                    Intent intent = new Intent(context, RegisterAccount.class);
                                    context.startActivity(intent);
                                    context.finish();
                                } else if (type == 0) {
                                    context.startActivity(new Intent(context, ProductInfoActivity.class).putExtra("goods_id", goods_id));
                                } else if (type == 1) {
                                    context.startActivity(new Intent(context, FastGoodsDetailActivity.class).putExtra("id", goods_id));
                                }
                            } else
                                ToastUtils.showToast("商品不存在");
                        } catch (
                                JSONException e
                                )

                        {
                            e.printStackTrace();
                        } catch (
                                UnsupportedEncodingException e
                                )

                        {
                            e.printStackTrace();
                        }
                    }
                }

        );
        //跳转到商品列表页
        webView.registerHandler("goods_list", new

                BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        try {
                            LogUtils.e("goods_list", URLDecoder.decode(s.toString(), "utf-8"));

                            JSONObject json = new JSONObject(URLDecoder.decode(s.toString(), "utf-8"));

                            String name = json.optString("title");
                            String keywords = json.optString("keywords");
                            String cate_id = json.optString("cate_id");
                            String brand_id = json.optString("brand_id");
                            String is_new = json.optString("is_new");

                            if (!(ViewUtils.isEmpty(cate_id) && ViewUtils.isEmpty(brand_id))) {
                                context.startActivity(new Intent(context, BrandInfoActivity.class)
                                        .putExtra("name", name)
                                        .putExtra("keywords", keywords)
                                        .putExtra("cate_id", cate_id)
                                        .putExtra("brand_id", brand_id)
                                        .putExtra("is_new", is_new));
                            }
                            if (ViewUtils.isEmpty(cate_id) && ViewUtils.isEmpty(brand_id)) {
                                Intent intent = new Intent(context, MeiQiFastBuyActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(intent);
                                context.finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }

        );

        //跳转到预售商品列表页
        webView.registerHandler("presale_goods_list", new

                        BridgeHandler() {
                            @Override
                            public void handler(String s, CallBackFunction callBackFunction) {
                                try {
                                    LogUtils.e("presale_goods_list", URLDecoder.decode(s.toString(), "utf-8"));
                                    JSONObject json = new JSONObject(URLDecoder.decode(s.toString(), "utf-8"));
                                    String cate_id = json.optString("cate_id");
                                    if (!TextUtils.isEmpty(cate_id)) {
                                        Intent intent = new Intent(context, MeiQiFastBuyActivity.class);
//                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        intent.putExtra("cate_id", cate_id);
                                        context.startActivity(intent);
                                    }
                                    if (ViewUtils.isEmpty(cate_id)) {
                                        Intent intent = new Intent(context, MeiQiFastBuyActivity.class);
//                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        context.startActivity(intent);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

        );
        /**
         * Intent参数
         * from: 1 (WebViewActivity)
         * where: 0(主界面) 1(分类) 2（品牌）
         * */
        webView.registerHandler("brand_list", new

                BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        Intent intent = new Intent(context, MainActivity.class);
                        intent.putExtra("from", 1);
                        intent.putExtra("where", 2);
                        context.startActivity(intent);
                        context.finish();
                    }
                }

        );
        webView.registerHandler("category_list", new

                BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        Intent intent = new Intent(context, MainActivity.class);
                        intent.putExtra("from", 1);
                        intent.putExtra("where", 1);
                        context.startActivity(intent);
                        context.finish();
                    }
                }

        );
        webView.registerHandler("home_page", new

                BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        Intent intent = new Intent(context, MainActivity.class);
                        intent.putExtra("from", 1);
                        intent.putExtra("where", 0);
                        context.startActivity(intent);
                        context.finish();
                    }
                }

        );
        webView.registerHandler("login_in", new

                BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        context.finish();
                    }
                }

        );
        webView.registerHandler("sign_in", new

                BridgeHandler() {
                    @Override
                    public void handler(String s, CallBackFunction callBackFunction) {
                        if (App.user.getLoginState()) {
                            //弹出对话框:您已是注册会员，是否退出登陆，重新注册
                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            builder.setTitle("退出登陆");
                            builder.setMessage("您已是注册会员，是否退出登陆，重新注册");
                            builder.setNegativeButton("取消", null);
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    requestLoginOUtFromServer(context);
                                }
                            });
                            builder.create().show();
                        }
                    }
                }

        );
    }

    private static void requestLoginOUtFromServer(final Activity context) {
        final LoginOutRequestFilter filter = new LoginOutRequestFilter((BaseParentActivity) context);
        /*filter.offerErrorParams(rootView);*/
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<String>() {
            @Override
            public void onSuccess(String result) {
                ToastUtils.showToast("退出登陆成功");
                App.user.setLoginState(false);
                App.user.removePassword();
                filter.saveTokenId(null);
                com.androidnetframe.utils.UIUtils.simpleStartActivity(RegisterAccount.class);
                context.finish();
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast("退出登陆失败");
            }
        });
    }

}
